<template>
  <div class="admin-page kcjxzj-summary-browse">
    <div class="page-header">
      <h1>浏览课程总结</h1>
    </div>
    
    <el-card class="table-card">
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="学期">
            <el-select v-model="filters.termId" placeholder="请选择学期" clearable style="width: 250px;">
              <el-option 
                v-for="term in terms" 
                :key="term.id" 
                :label="term.name" 
                :value="term.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程名称">
            <el-select
              v-model="filters.courseId"
              v-model:input-value="filters.courseName"
              placeholder="请输入或选择课程"
              clearable
              filterable
              allow-create
              default-first-option
              style="width: 400px;"
              @input="handleCourseSelect"
              @create="handleCourseCreate"
            >
              <el-option
                v-for="course in filteredCourses"
                :key="course.id"
                :label="course.name"
                :value="course.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filters.status" placeholder="请选择状态" clearable style="width: 180px;">
              <el-option 
                v-for="status in statusOptions" 
                :key="status.value" 
                :label="status.label" 
                :value="status.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchSummaries">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredSummaries"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column label="课程名称" min-width="120" resizable>
          <template #default="scope">
            {{ getCourseNameById(scope.row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column label="教师" min-width="100" resizable>
          <template #default="scope">
            {{ getTeacherNameById(scope.row.teacherId) }}
          </template>
        </el-table-column>
        <el-table-column label="学期" min-width="100" resizable>
          <template #default="scope">
            {{ getTermNameById(scope.row.termId) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="150" resizable>
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.statusId)" 
              size="small"
            >
              {{ getStatusName(scope.row.statusId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="200" resizable>
          <template #default="scope">
            <el-button size="small" @click="viewSummary(scope.row.id)">
              <el-icon><View /></el-icon> 查看
            </el-button>
            <el-button size="small" type="primary" @click="editSummary(scope.row.id)" 
                      v-if="canEdit(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="warning" @click="submitSummary(scope.row.id)" 
                      v-if="canSubmit(scope.row)">
              <el-icon><Upload /></el-icon> 提交
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加详情对话框 -->
    <SummaryViewDialog
      v-model:visible="summaryDialogVisible"
      :summaryId="currentSummaryId"
      @close="handleDialogClose"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { getMyKcjxzj, submitKcjxzj } from '@/api/course-teaching-summary';
import { courseApi, termApi } from '@/api/base-data';
import { getAllUsersList } from '@/api/user';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { View, Edit, Upload, Plus } from '@element-plus/icons-vue';
import SummaryViewDialog from '@/components/common/SummaryViewDialog.vue'; // 引入详情对话框组件

export default {
  components: {
    View,
    Edit,
    Upload,
    Plus,
    SummaryViewDialog // 注册组件
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    const summaries = ref([])
    const courses = ref([])
    const terms = ref([])
    const teachers = ref([])
    const loading = ref(false)
    
    // 详情对话框相关
    const summaryDialogVisible = ref(false)
    const currentSummaryId = ref(null)
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 状态选项常量
    const statusOptions = ref([
      { value: 1, label: '未提交' },
      { value: 2, label: '已提交' },
      { value: 3, label: '已教研室审核通过' },
      { value: 4, label: '已部系审核通过' },
      { value: 5, label: '教研室审核未通过' },
      { value: 6, label: '部系审核未通过' }
    ]);
    
    // 筛选条件
    const filters = reactive({
      termId: '',
      courseId: '',
      courseName: '',
      status: ''
    })

    // 获取所有课程
    const fetchCourses = async () => {
      try {
        courses.value = await courseApi.getAllCourses();
      } catch (error) {
        ElMessage.error('获取课程列表失败');
      }
    };
    
    // 获取当前学期并设置为默认值
    const getCurrentTerm = (terms) => {
      // 查找标记为当前学期的记录
      const currentTerm = terms.find(term => term.isCurrent === true || term.is_current === true);
      
      // 如果没有找到当前学期，返回null（不设置默认值）
      if (!currentTerm && terms.length > 0) {
      }
      
      return currentTerm || null;
    };

    // 获取所有学期
    const fetchTerms = async () => {
      try {
        terms.value = await termApi.getAllTerms();
        
        // 设置当前学期为默认值
        const currentTerm = getCurrentTerm(terms.value);
        if (currentTerm) {
          filters.termId = currentTerm.id;
        }
      } catch (error) {
        ElMessage.error('获取学期列表失败');
      }
    };
    
    // 获取教学总结
    const fetchSummaries = async () => {
      loading.value = true;
      try {
        // 使用getMyKcjxzj获取自己撰写的课程教学总结
        summaries.value = await getMyKcjxzj();
        // 更新总数
        total.value = summaries.value.length;
      } catch (error) {
        ElMessage.error('获取总结列表失败');
      } finally {
        loading.value = false;
      }
    }
    
    // 获取所有教师
    const fetchTeachers = async () => {
      try {
        // 检查当前用户是否有权限获取所有用户数据
        if (userStore.isAdmin || userStore.isDepartmentHead || userStore.isResearchHead) {
          // 管理员、部门主管或研究室主管可以获取所有用户数据
          const users = await getAllUsersList(); // 使用列表接口而不是分页接口
          // 确保users是数组格式，过滤出教师角色的用户
          const userArray = Array.isArray(users) ? users : (users.content || []);
          teachers.value = userArray.filter(user => 
            user.roles && user.roles.some(role => role.name === 'ROLE_TEACHER')
          );
        } else {
          // 普通教师只需要自己的信息（可以从userStore获取）
          teachers.value = [{
            id: userStore.userId,
            name: userStore.name || userStore.username,
            username: userStore.username,
            roles: [{ name: 'ROLE_TEACHER' }]
          }];
        }
      } catch (error) {
        ElMessage.error('获取教师列表失败');
      }
    };
    
    // 根据课程名称过滤课程列表（用于下拉选择）
    const filteredCourses = computed(() => {
      if (!filters.courseName) {
        return courses.value;
      }
      return courses.value.filter(course =>
        course.name.toLowerCase().includes(filters.courseName.toLowerCase())
      );
    });
    
    // 处理课程选择
    const handleCourseSelect = (value) => {
      if (value) {
        // 选择了现有课程，设置课程名称
        const selectedCourse = courses.value.find(course => course.id === value);
        if (selectedCourse) {
          filters.courseName = selectedCourse.name;
        }
      } else {
        // 清空选择，清空课程名称
        filters.courseName = '';
      }
    };
    
    // 处理新课程创建
    const handleCourseCreate = (newCourseName) => {
      if (newCourseName && !courses.value.some(course => course.name === newCourseName)) {
        // 这里可以添加创建新课程的逻辑
        // 目前只是设置课程名称，不实际创建课程
        filters.courseName = newCourseName;
        filters.courseId = ''; // 清空课程ID，表示这是一个新输入
      }
    };
    
    // 根据筛选条件过滤数据
    const filteredSummaries = computed(() => {
      let filtered = summaries.value;
      
      if (filters.termId) {
        filtered = filtered.filter(summary =>
          summary.termId === filters.termId
        );
      }
      
      // 课程ID过滤（精确匹配）
      if (filters.courseId) {
        filtered = filtered.filter(summary =>
          summary.courseId === filters.courseId
        );
      }
      
      // 课程名称模糊搜索（当没有选择具体课程ID时）
      if (filters.courseName && !filters.courseId) {
        filtered = filtered.filter(summary => {
          const courseName = getCourseNameById(summary.courseId);
          return courseName && courseName.toLowerCase().includes(filters.courseName.toLowerCase());
        });
      }
      
      if (filters.status !== '' && filters.status !== null) {
        filtered = filtered.filter(summary =>
          summary.statusId === filters.status
        );
      }
      
      // 更新总数
      total.value = filtered.length;
      
      // 返回当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return filtered.slice(startIndex, startIndex + pageSize.value);
    })
    
    // 搜索总结
    const searchSummaries = () => {
      currentPage.value = 1
      // 过滤逻辑已在 computed 中实现
    }
    
    // 根据课程名称搜索
    const searchCourseByName = () => {
      // 当输入课程名称时，清空课程ID选择
      if (filters.courseName) {
        filters.courseId = ''
      }
      // 搜索逻辑已在 computed 中实现
    }
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.termId = ''
      filters.courseId = ''
      filters.courseName = ''
      filters.status = ''
      currentPage.value = 1
    }
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }

    const navigateToCreate = () => {
      router.push('/kcjxzj/summary-create')
    }

    const viewSummary = (id) => {
      if (!id) {
        ElMessage.warning('总结ID无效，无法查看详情');
        return;
      }
      
      // 修改查看方法，打开对话框而不是路由跳转
      currentSummaryId.value = id;
      summaryDialogVisible.value = true;
    }

    const editSummary = (id) => {
      // 查找对应的总结数据
      const summary = summaries.value.find(s => s.id === id);
      const query = {};
      
      // 如果总结有关联的教学任务，传递第一个教学任务ID作为missionId
      if (summary && summary.teachingMissionIds && summary.teachingMissionIds.length > 0) {
        query.missionId = summary.teachingMissionIds[0];
      }
      
      router.push({
        path: `/kcjxzj/summary-edit/${id}`,
        query: query
      });
    }
    
    const submitSummary = async (id) => {
      try {
        await submitKcjxzj(id)
        ElMessage.success('提交成功')
        fetchSummaries()
      } catch (error) {
        ElMessage.error('提交失败')
      }
    }

    const handleDialogClose = () => {
      // 对话框关闭后的处理
      currentSummaryId.value = null;
      summaryDialogVisible.value = false;
      
      // 可以选择性地刷新列表数据
      // 如果在查看详情后可能有状态变更，则取消下面的注释
      // fetchSummaries();
    }

    const canEdit = (summary) => {
      // 只有创建者且状态为未提交或审核未通过时才能编辑
      return summary.teacherId === userStore.userId && 
             (summary.statusId === 1 || summary.statusId === 5 || summary.statusId === 6);
    };
    
    const canSubmit = (summary) => {
      // 只有创建者且状态为未提交或审核未通过时才能提交
      return summary.teacherId === userStore.userId && 
             (summary.statusId === 1 || summary.statusId === 5 || summary.statusId === 6);
    };
    
    const getStatusType = (status) => {
      switch (status) {
        case 0:
          return 'info' // 灰色 - 未创建
        case 1:
          return 'warning' // 黄色 - 未提交
        case 2:
          return 'primary' // 蓝色 - 已提交
        case 3:
          return 'success' // 绿色 - 已教研室审核通过
        case 4:
          return 'success' // 绿色 - 已部系审核通过
        case 5:
          return 'danger' // 红色 - 教研室审核未通过
        case 6:
          return 'danger' // 红色 - 部系审核未通过
        default:
          return 'info' // 默认使用info类型
      }
    };
    
    // 获取状态名称
    const getStatusName = (statusId) => {
      if (statusId === undefined || statusId === null) return '-';
      const status = statusOptions.value.find(s => s.value === statusId);
      return status ? status.label : '-';
    };

    // 根据ID获取课程名称
    const getCourseNameById = (courseId) => {
      if (!courseId) return '-';
      const course = courses.value.find(c => c.id === courseId);
      return course ? course.name : '-';
    };
    
    // 根据ID获取学期名称
    const getTermNameById = (termId) => {
      if (!termId) return '-';
      const term = terms.value.find(t => t.id === termId);
      return term ? term.name : '-';
    };
    
    // 根据ID获取教师名称
    const getTeacherNameById = (teacherId) => {
      if (!teacherId) return '-';
      // 因为教师数据不是从课程或学期中获取的，我们需要从总结数据中提取教师信息
      // 或者单独获取教师数据
      const teacher = teachers.value.find(t => t.id === teacherId);
      return teacher ? teacher.name : '-';
    };

    onMounted(async () => {
      // 先获取学期和课程数据，设置默认学期
      await Promise.all([fetchCourses(), fetchTerms(), fetchTeachers()]);
      // 然后获取总结数据（会使用默认学期过滤）
      await fetchSummaries();
    });

    return {
      filteredSummaries,
      filteredCourses,
      loading,
      filters,
      courses,
      terms,
      statusOptions,
      currentPage,
      pageSize,
      total,
      searchSummaries,
      searchCourseByName,
      handleCourseSelect,
      handleCourseCreate,
      resetFilters,
      handlePageChange,
      navigateToCreate,
      viewSummary,
      editSummary,
      submitSummary,
      canEdit,
      canSubmit,
      getStatusType,
      getStatusName,
      getCourseNameById,
      getTermNameById,
      getTeacherNameById,
      // 添加新的返回值
      summaryDialogVisible,
      currentSummaryId,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
/* 特定于课程教学总结列表页面的样式可以放在这里 */
.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.filter-form .el-form-item {
  margin-right: 10px;
  margin-bottom: 15px;
}
</style>
